/**
 * 雷达图组件
 * 用于展示多维数据的对比
 */

import React from 'react';
import { Chart as ChartJS, RadialLinearScale, PointElement, LineElement, Filler, Title, Tooltip, Legend } from 'chart.js';
import { Radar } from 'react-chartjs-2';
import { ChartData, ChartOptions } from '../types';

ChartJS.register(RadialLinearScale, PointElement, LineElement, Filler, Title, Tooltip, Legend);

interface RadarChartProps {
  data: ChartData;
  options?: ChartOptions;
  height?: number;
}

const RadarChart: React.FC<RadarChartProps> = ({
  data,
  options,
  height = 400,
}) => {
  // 雷达图只使用第一个数据集
  if (!data.datasets || data.datasets.length === 0) {
    return null;
  }

  const firstDataset = data.datasets[0];
  
  // 构建雷达图数据
  const radarData = {
    labels: data.labels,
    datasets: [
      {
        label: firstDataset.label || '数据',
        data: firstDataset.data,
        backgroundColor: firstDataset.backgroundColor 
          ? (Array.isArray(firstDataset.backgroundColor) 
              ? firstDataset.backgroundColor[0] 
              : firstDataset.backgroundColor)
          : 'rgba(54, 162, 235, 0.2)',
        borderColor: firstDataset.borderColor
          ? (Array.isArray(firstDataset.borderColor)
              ? firstDataset.borderColor[0]
              : firstDataset.borderColor)
          : 'rgba(54, 162, 235, 1)',
        borderWidth: firstDataset.borderWidth || 2,
        fill: true,
        pointBackgroundColor: firstDataset.borderColor
          ? (Array.isArray(firstDataset.borderColor)
              ? firstDataset.borderColor[0]
              : firstDataset.borderColor)
          : 'rgba(54, 162, 235, 1)',
        pointBorderColor: '#fff',
        pointHoverBackgroundColor: '#fff',
        pointHoverBorderColor: firstDataset.borderColor
          ? (Array.isArray(firstDataset.borderColor)
              ? firstDataset.borderColor[0]
              : firstDataset.borderColor)
          : 'rgba(54, 162, 235, 1)',
      },
    ],
  };

  // 计算数据范围与“合适”的步长，使中心点为（最小刻度 - 步长）
  const getAllValues = (): number[] => {
    try {
      const ds = (data?.datasets || []) as any[];
      const vals: number[] = [];
      ds.forEach(d => {
        if (Array.isArray(d?.data)) {
          d.data.forEach((v: any) => {
            const num = typeof v === 'number' ? v : Number(v);
            if (!Number.isNaN(num)) vals.push(num);
          });
        }
      });
      return vals;
    } catch { return []; }
  };

  const values = getAllValues();
  const dataMin = values.length ? Math.min(...values) : 0;
  const dataMax = values.length ? Math.max(...values) : 1;
  const range = Math.max(1e-9, dataMax - dataMin);

  const niceStep = (r: number): number => {
    // 目标刻度数量约 5
    const targetTicks = 5;
    const rough = r / targetTicks;
    const pow10 = Math.pow(10, Math.floor(Math.log10(rough)));
    const candidates = [1, 2, 5, 10].map(m => m * pow10);
    // 选择最接近 rough 的候选
    let best = candidates[0];
    let bestDiff = Math.abs(candidates[0] - rough);
    for (let i = 1; i < candidates.length; i++) {
      const diff = Math.abs(candidates[i] - rough);
      if (diff < bestDiff) { best = candidates[i]; bestDiff = diff; }
    }
    return best > 0 ? best : pow10;
  };

  const stepSize = niceStep(range);
  const minTick = Math.floor(dataMin / stepSize) * stepSize;
  const rMin = Math.max(0, minTick - stepSize); // 中心应为最小刻度减去一个步长，但不小于0
  const rMax = Math.ceil(dataMax / stepSize) * stepSize;

  // 雷达图选项：从外部选项开始合并，但强制关闭 x/y 轴，并保证 r 轴配置生效
  const incomingOptions: any = options || {};
  const chartOptions: any = {
    ...incomingOptions,
    responsive: true,
    maintainAspectRatio: false,
    layout: {
      padding: 20,
      ...(incomingOptions.layout || {}),
    },
    elements: {
      line: { borderWidth: 2, ...(incomingOptions.elements?.line || {}) },
      point: { radius: 4, hoverRadius: 6, ...(incomingOptions.elements?.point || {}) },
      ...(incomingOptions.elements || {}),
    },
    plugins: {
      legend: {
        display: true,
        position: 'top' as const,
        labels: { padding: 15, usePointStyle: true, font: { size: 12 }, ...(incomingOptions.plugins?.legend?.labels || {}) },
        ...(incomingOptions.plugins?.legend || {}),
      },
      tooltip: {
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        padding: 12,
        titleFont: { size: 14 },
        bodyFont: { size: 12 },
        callbacks: {
          label: function(context: any) {
            const label = context.dataset.label || '';
            const value = context.parsed?.r ?? context.raw ?? 0;
            return `${label}: ${Number(value).toFixed(2).toLocaleString()}`;
          },
          ...(incomingOptions.plugins?.tooltip?.callbacks || {}),
        },
        ...(incomingOptions.plugins?.tooltip || {}),
      },
      ...(incomingOptions.plugins || {}),
    },
    scales: {
      // 先合并外部的 scales，再强制设置 x/y 隐藏与 r 轴配置
      ...(incomingOptions.scales || {}),
      x: {
        ...(incomingOptions.scales?.x || {}),
        display: false,
        grid: { ...(incomingOptions.scales?.x?.grid || {}), display: false },
        ticks: { ...(incomingOptions.scales?.x?.ticks || {}), display: false },
      },
      y: {
        ...(incomingOptions.scales?.y || {}),
        display: false,
        grid: { ...(incomingOptions.scales?.y?.grid || {}), display: false },
        ticks: { ...(incomingOptions.scales?.y?.ticks || {}), display: false },
      },
      r: {
        min: Number.isFinite(rMin) ? rMin : undefined,
        max: Number.isFinite(rMax) ? rMax : undefined,
        angleLines: { color: 'rgba(0, 0, 0, 0.1)', ...(incomingOptions.scales?.r?.angleLines || {}) },
        grid: { color: 'rgba(0, 0, 0, 0.1)', ...(incomingOptions.scales?.r?.grid || {}) },
        pointLabels: { font: { size: 12 }, ...(incomingOptions.scales?.r?.pointLabels || {}) },
        ticks: { 
          backdropColor: 'transparent', 
          beginAtZero: false,
          stepSize: stepSize,
          ...(incomingOptions.scales?.r?.ticks || {}) 
        },
        ...(incomingOptions.scales?.r || {}),
      },
    },
  };

  return (
    <div style={{ 
      width: '100%', 
      height: `${height}px`, 
      position: 'relative' 
    }}>
      <Radar data={radarData as any} options={chartOptions} />
    </div>
  );
};

export default RadarChart;

